<?php
namespace Hangpu888\Hpadmin\model;

use Hangpu888\Hpadmin\Model;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\manager\DataManager;

class AdminRole extends Model
{
    // 自动时间戳
    protected $autoWriteTimestamp = 'datetime';
    // 定义时间戳字段名
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';
    
    // 设置JSON字段转换
    protected $json = ['rule'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    /**
     * 显示表格数据
     *
     * @return ListBuilder
     */
    public function showListView(): ListBuilder
    {
        $builder = new ListBuilder;
        $builder = $builder
            ->addColumn('id', '序号', [
                'width'         => '80'
            ])
            ->addColumn('ctime', '创建时间')
            ->addColumn('utime', '更新时间')
            ->addColumn('title', '职位名称')
            ->addColumn('is_system_text', '禁止删除');
        return $builder;
    }

    /**
     * 显示表单数据
     *
     * @return FormBuilder
     */
    public function showFormView() : FormBuilder
    {
        $builder = new FormBuilder;
        $builder = $builder
            ->addRow('title', 'input', '职位名称');
        return $builder;
    }

    /**
     * 显示授权视图
     *
     * @return FormBuilder
     */
    public function showAuthView() : FormBuilder
    {
        $rule = AuthRule::orderBy('id','asc')->select('path','pid','title')->get()->toArray();
        $rule = DataManager::channelLevel($rule,'','','path','pid');
        $authRule = $this->getAuthRule($rule);
        $builder = new FormBuilder;
        $builder = $builder
        ->addRow('title','custom','角色名称','',[
            'type'                  => 'info',
        ])
        ->addRow('rule','tree','权限授权',[],[
            'data'                  => $authRule,
            'showCheckbox'          => true,
            'defaultExpandAll'      => true
        ]);
        return $builder;
    }

    /**
     * 获取权限列表
     *
     * @param array $rule
     * @return array
     */
    public function getAuthRule(array $rule) : array
    {
        $list = [];
        $i = 0;
        foreach ($rule as $value)
        {
            $list[$i]['title'] = $value['title'];
            $list[$i]['id'] = $value['path'];
            if ($value['_data'])
            {
                $list[$i]['children'] = $this->getAuthRule($value['_data']);
            }
            $i++;
        }
        return $list;
    }

    /**
     * 获取角色的表单option数据
     *
     * @return array
     */
    public function getRoleOptions() : array
    {
        $list = $this->order('id asc')->field('id,title')->select()->toArray();
        $data = [];
        foreach ($list as $key => $value)
        {
            $data[$key]['label'] = $value['title'];
            $data[$key]['value'] = $value['id'];
        }
        return $data;
    }
}
